﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using Microsoft.Office.InfoPath;

namespace InfoPathDebugger.RuleManager
{
    public class QueryActionExecutor : IActionExecutor
    {
        #region IActionExecutor Members

        public void Execute(XPathNavigator actionNav, XPathNavigator dataSourceNav, Object additionalData)
        {
            if (!additionalData.GetType().BaseType.Equals(typeof(DataConnectionCollection)))
            {
                throw new MemberAccessException("The additional data is not a Microsoft.Office.InfoPath.DataConnectionCollection object.");
            }

            // Convert to data connection collection.
            DataConnectionCollection dataConnections = (DataConnectionCollection)additionalData;

            // Get the adapter attribute value. This value is used as the key word to retrieve data connection from InfoPath.
            String adapter = actionNav.GetAttribute("adapter", String.Empty);

            // Retrieve a data connection to execute.
            DataConnection dataConnection = dataConnections[adapter];
            if (dataConnection == null)
            {
                throw new ApplicationException(String.Format("Can't find data connection '{0}'", adapter));
            }

            dataConnection.Execute();
        }

        #endregion
    }
}
